package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.gather.api.domain.ErpCollectProductExpand;
import com.erp.gather.domain.bo.ErpCollectProductSkuBo;
import com.ruoyi.gather.api.domain.vo.ErpCollectProductSkuVo;
import com.erp.gather.mapper.ErpCollectProductExpandMapper;
import com.erp.gather.mapper.ErpCollectProductSkuMapper;
import com.erp.gather.service.IErpCollectProductSkuService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）Service业务层处理
 *
 * @author erp
 * @date 2023-03-07
 */
@RequiredArgsConstructor
@Service
public class ErpCollectProductSkuServiceImpl implements IErpCollectProductSkuService {

    private final ErpCollectProductSkuMapper baseMapper;
    private final ErpCollectProductExpandMapper collectProductExpandMapper;

    /**
     * 查询采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public ErpCollectProductSkuVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public TableDataInfo<ErpCollectProductSkuVo> queryPageList(ErpCollectProductSkuBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpCollectProductSku> lqw = buildQueryWrapper(bo);
        Page<ErpCollectProductSkuVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public List<ErpCollectProductSkuVo> queryList(ErpCollectProductSkuBo bo) {
        LambdaQueryWrapper<ErpCollectProductSku> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询采集商品SKU列表
     */
    @Override
    public List<ErpCollectProductSku> queryCollectProductSkuList(ErpCollectProductSku collectProductSku){
        // 暂只用到这些条件，后续需要其他条件，自行添加
        return baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, collectProductSku.getSkuCode())
                        );
    }


    private LambdaQueryWrapper<ErpCollectProductSku> buildQueryWrapper(ErpCollectProductSkuBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpCollectProductSku> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCollectProductId() != null, ErpCollectProductSku::getCollectProductId, bo.getCollectProductId());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuCode()), ErpCollectProductSku::getSkuCode, bo.getSkuCode());
        lqw.like(StringUtils.isNotBlank(bo.getSkuName()), ErpCollectProductSku::getSkuName, bo.getSkuName());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuNameEn()), ErpCollectProductSku::getSkuNameEn, bo.getSkuNameEn());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuImage()), ErpCollectProductSku::getSkuImage, bo.getSkuImage());
        lqw.eq(StringUtils.isNotBlank(bo.getImageUrlList()), ErpCollectProductSku::getImageUrlList, bo.getImageUrlList());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectSkuPrice()), ErpCollectProductSku::getCollectSkuPrice, bo.getCollectSkuPrice());
        lqw.eq(bo.getSkuLength() != null, ErpCollectProductSku::getSkuLength, bo.getSkuLength());
        lqw.eq(bo.getSkuWidth() != null, ErpCollectProductSku::getSkuWidth, bo.getSkuWidth());
        lqw.eq(bo.getSkuHeight() != null, ErpCollectProductSku::getSkuHeight, bo.getSkuHeight());
        lqw.eq(bo.getSkuWeight() != null, ErpCollectProductSku::getSkuWeight, bo.getSkuWeight());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuLink()), ErpCollectProductSku::getSkuLink, bo.getSkuLink());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuPrice()), ErpCollectProductSku::getSkuPrice, bo.getSkuPrice());
        lqw.eq(bo.getSkuStock() != null, ErpCollectProductSku::getSkuStock, bo.getSkuStock());
        lqw.eq(StringUtils.isNotBlank(bo.getSkuPropertyIds()), ErpCollectProductSku::getSkuPropertyIds, bo.getSkuPropertyIds());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpCollectProductSku::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean insertByBo(ErpCollectProductSkuBo bo) {
        ErpCollectProductSku add = BeanUtil.toBean(bo, ErpCollectProductSku.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean updateByBo(ErpCollectProductSkuBo bo) {
        ErpCollectProductSku update = BeanUtil.toBean(bo, ErpCollectProductSku.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpCollectProductSku entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采集商品SKU;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public R<Object> getOrderSkuBuyLink(String skuCode) {
        List<ErpCollectProductSku> skuList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
        );
        if (skuList.get(0) == null) {
            return R.fail("未查找到该商品");
        }
//        List<String> imageURLList = ListUtil.toList(sku.getSkuBuyLink().split(","));
        return R.ok("已查找到", skuList.get(0).getSkuBuyLink());

    }

    @Override
    public R<Object> updateOrderSkuBuyLink(String skuCode, String skuBuyLink) {
        ErpCollectProductSku sku = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
        );
        if (sku == null) {
            return R.fail("未查找到该商品");
        }
        sku.setSkuBuyLink(skuBuyLink);
        if (baseMapper.updateById(sku) > 0) {
            return R.ok("已更新" + skuCode + "的采购链接");
        } else {
            return R.fail("更新采购链接失败");
        }
    }

    @Override
    public String getSpecBySkuCde(String skuCode, boolean isSplit) {
        List<ErpCollectProductSku> skuList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
        );
        ErpCollectProductSku sku = skuList.get(0);
        String skuProperty = "";
        if (sku != null) {
            String skuPropertyIds = sku.getSkuPropertyIds();
            Long collectProductId = sku.getCollectProductId();
            if (collectProductId != null) {
                if (StringUtils.isNotEmpty(skuPropertyIds)) {
                    String[] split = skuPropertyIds.split(";");
                    for (int i = 0; i < split.length; i++) {
                        String[] propertyList = split[i].split(":");
                        for (int j = 0; j < propertyList.length; j++) {
                            if ((j + 1) % 2 == 1) {
                                ErpCollectProductExpand collectProductExpand = collectProductExpandMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>().eq(ErpCollectProductExpand::getCollectProductId, collectProductId));
                                String skuPropertyJson = collectProductExpand.getSkuProperty();
                                JSONArray keyAndValueArray = JSON.parseArray(skuPropertyJson);
                                for (int i1 = 0; i1 < keyAndValueArray.size(); i1++) {
                                    JSONObject jsonObject = keyAndValueArray.getJSONObject(i1);
                                    String keyValue = jsonObject.getString("value");
                                    if (propertyList[j].equals(keyValue)) {
                                        String name = jsonObject.getString("name");
                                        skuProperty = "".equals(skuProperty) ? name + "：" : skuProperty + name + "：";
                                        JSONArray list = jsonObject.getJSONArray("list");
                                        for (int i2 = 0; i2 < list.size(); i2++) {
                                            JSONObject valueObject = list.getJSONObject(i2);
                                            String value = valueObject.getString("value");
                                            if (propertyList[j + 1].equals(value)) {
                                                String valueName = valueObject.getString("name");
                                                skuProperty = skuProperty + valueName + "；";
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    skuProperty = skuProperty.substring(0, skuProperty.length() - 1);
                }
            }
        }
        if (isSplit) {
            if (!skuProperty.isEmpty()) {
                String replaceAll = skuProperty.replaceAll("：", "；");
                List<String> collect = Arrays.stream(replaceAll.split("；")).collect(Collectors.toList());
                StringBuilder string = new StringBuilder();
                for (int i = 0; i < collect.size(); i++) {
                    if ((i + 1) % 2 == 0) {
                        string.append(collect.get(i)).append("；");
                    }
                }
                if (StringUtils.isNotEmpty(string.toString())) {
                    string = new StringBuilder(string.substring(0, string.length() - 1));
                    skuProperty = string + "";
                }
            }
        }
        return skuProperty;
    }

    @Override
    public String getSpecBySkuCodeNew(String skuCode) {
        List<ErpCollectProductSku> skuList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
        );
        String skuProperty = new String();
        if (skuList.size() > 0) {
            ErpCollectProductSku sku = skuList.get(0);

            String skuPropertyIds = sku.getSkuPropertyIds();
            Long collectProductId = sku.getCollectProductId();
            if (Objects.nonNull(collectProductId) && Objects.nonNull(skuPropertyIds)) {
                skuProperty = processSkuPropertyIds(skuPropertyIds, collectProductId.toString());
            }
        }
        return skuProperty;
    }

    @Override
    public R<Object> getCollectProductSkuInfo(ErpCollectProductSku erpCollectProductSkuSel) {
        ErpCollectProductSkuBo bo = BeanUtil.copyProperties(erpCollectProductSkuSel, ErpCollectProductSkuBo.class);
        ErpCollectProductSku sku = baseMapper.selectOne(buildQueryWrapper(bo).last("limit 1"));
        if (Objects.isNull(sku)){
            return R.fail("未查找到信息");
        }else {
            return R.ok(sku);
        }
    }

    @Override
    public R<Object> getCollectProductSkuListInfo(ErpCollectProductSku erpCollectProductSkuSel) {
        ErpCollectProductSkuBo bo = BeanUtil.copyProperties(erpCollectProductSkuSel, ErpCollectProductSkuBo.class);
       List< ErpCollectProductSku> skuList = baseMapper.selectList(buildQueryWrapper(bo));
        if (Objects.isNull(skuList)){
            return R.fail("未查找到信息");
        }else {
            return R.ok(skuList);
        }
    }

    @Override
    public ErpCollectProductSku getSkuInfoBySkuCode(String skuCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getSkuCode,skuCode));
    }

    @Override
    public R<Object> getImageBySkuCodeNew(String skuCode) {
        ErpCollectProductSku sku = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductSku>()
                        .eq(ErpCollectProductSku::getSkuCode, skuCode)
                        .eq(ErpCollectProductSku::getDelFlag, "0")
        );
        if (Objects.isNull(sku.getSkuImage())){
            return R.fail("图片不存在");
        }else {
            return R.ok(sku.getSkuImage());
        }
    }

    public String processSkuPropertyIds(String skuPropertyIds, String collectProductId) {
        String skuProperty = new String();
        List<String> split = Arrays.stream(skuPropertyIds.split(";")).collect(Collectors.toList());

//        String[] split = skuPropertyIds.split(";");
        for (String pair : split) {
            String[] propertyList = pair.split(":");
            if (propertyList.length % 2 != 1) {
                ErpCollectProductExpand collectProductExpand = null;
                try {
                    collectProductExpand = collectProductExpandMapper.selectOne(
                            new LambdaQueryWrapper<ErpCollectProductExpand>()
                                    .eq(ErpCollectProductExpand::getCollectProductId, collectProductId)
                    );
                } catch (Exception e) {
                    // Handle exception, e.g., log it or throw a custom exception
                    e.printStackTrace();
                    continue;
                }
                if (collectProductExpand == null) {
                    continue;
                }
                String skuPropertyJson = collectProductExpand.getSkuProperty();
                JSONArray keyAndValueArray = JSON.parseArray(skuPropertyJson);
                for (int i1 = 0; i1 < keyAndValueArray.size(); i1++) {
                    JSONObject jsonObject = keyAndValueArray.getJSONObject(i1);
                    String keyValue = jsonObject.getString("value");
                    if (propertyList[0].equals(keyValue)) {
                        String name = jsonObject.getString("name");
                        skuProperty = "".equals(skuProperty) ? name + "：" : skuProperty + name + "：";
                        JSONArray list = jsonObject.getJSONArray("list");
                        String valueName = findValueName(list, propertyList[1]);
                        if (valueName != null) {
                            skuProperty = skuProperty + valueName + "；";
                            break;  // No need to continue the loop since we found the value
                        }
                    }
                }
            }
        }
        if (skuProperty.length() > 0) {
            skuProperty = skuProperty.substring(0, skuProperty.length() - 1);
        }
        return skuProperty;
    }

    private String findValueName(JSONArray list, String value) {
        for (int i2 = 0; i2 < list.size(); i2++) {
            JSONObject valueObject = list.getJSONObject(i2);
            String currentValue = valueObject.getString("value");
            if (value.equals(currentValue)) {
                return valueObject.getString("name");
            }
        }
        return null;  // Return null if we didn't find the value
    }


}
